package com.woniuxy.classdeans.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.classdeans.exception.ClassdeansException;
import com.woniuxy.classdeans.service.ForemanInfoDtoService;
import com.woniuxy.classdeans.service.StudentScoreService;
import com.woniuxy.commons.entity.StudentInfo;
import com.woniuxy.commons.entity.wyh.ForemanInfoDto;
import com.woniuxy.commons.entity.wyh.ResponseTable;
import com.woniuxy.commons.entity.wyh.TeamInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 老师带班数据
 *
 * @author 王艳辉
 * @date 2020/8/1 - 11:08
 */
@RestController
@RequestMapping("ForemanInfoDto")
@Slf4j
@Transactional
public class ForemanInfoDtoController {

    @Autowired
    private ForemanInfoDtoService foremanInfoDtoService;

    //学生成绩信息
    @Autowired
    private StudentScoreService studentScoreService;

    /**
     * 获取所有班主任信息，包括班主任所带班级和班级的学生信息
     *
     * @return
     */
    @RequestMapping("getAll")
    public Object getAll(Integer page, Integer limit) {
        //返回消息类型,默认失败
        ResponseTable<ForemanInfoDto> res = new ResponseTable<ForemanInfoDto>().setCode(400).setMsg("获取老师信息失败！");

        try {
            if (page != null && limit != null)
                PageHelper.startPage(page, limit);//分页插件

            //获取分页班主任带班信息
            List<ForemanInfoDto> all = foremanInfoDtoService.getAll();

            PageInfo<ForemanInfoDto> pages = new PageInfo<>(all);//转换为分页对象可获取分页信息

            List<ForemanInfoDto> data = pages.getList();//数据

            //遍历数据
            for (ForemanInfoDto dto : data) {
                //班主任所带班级不为空
                if (dto.getTeamInfos() != null && dto.getTeamInfos().size() > 0) {

                    //遍历班级信息
                    for (TeamInfo team : dto.getTeamInfos()) {
                        //班级学生不为空
                        if (team.getStudentInfos() != null && team.getStudentInfos().size() > 0) {

                            for (StudentInfo stin : team.getStudentInfos()) {
                                //获得班级的学生成绩数据注入到学生实体
                                stin.setStudentScores(studentScoreService.getByStuid(stin.getStuid()));
                            }
                        }
                    }

                }


            }

            if (all != null) {
                //数据返回给前端
                res.setCode(0).setMsg("获取老师信息成功！").setData(all).setCount((int) pages.getTotal());
            }
        } catch (Exception e) {
            log.error(e.getMessage());//日志记录
            //抛自定义异常
            throw new ClassdeansException("ForemanInfoDto/getall异常");
        }


        return res;
    }
}
